<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>图片压缩</title>

    <!-- <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> -->
    <!-- <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> -->
    <!-- import Vue before Element -->
    <!-- <script src="https://unpkg.com/vue/dist/vue.js"></script> -->

    <!-- import JavaScript -->
    <!-- <script src="https://unpkg.com/element-ui/lib/index.js"></script> -->
    <!-- 动画 -->
    <!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css"> -->
    <!-- 基础样式 -->
    <!-- <link rel="stylesheet" href="index.css"> -->


    <link rel="stylesheet" href="cdn/index.css">
    <!-- import Vue before Element -->
    <script src="cdn/vue.min.js"></script>

    <!-- import JavaScript -->
    <script src="cdn/index.js"></script>
    <!-- 动画 -->
    <link rel="stylesheet" href="cdn/animate.min.css">
    <!-- 基础样式 -->
    <link rel="stylesheet" href="index.css">

</head>
<script>
</script>

<body>
    <!-- <h1 class="animated  fadeInDown faster">Example</h1> -->
    <div class="content" id="vue">
        <img class="settingIcon" src="./assets/settingIcon.png" @click="showSetting" />
        <!-- modal弹窗 -->
        <transition name="slide-fade"></transition>
        <div class="modal " v-show="isShowModal">
            <div class="content animated faster fadeInDown">
                <div class="header">
                    设置
                    <img class="closeIcon" src="./assets/close.png" @click="closeSetting" />
                </div>
                <div class="lineDiv">
                    <span>是否覆盖原图片:</span>
                    <el-switch v-model="isCover" active-color="#13ce66" />
                </div>
                <div class="lineDiv">
                    <span>图片保存地址:</span>

                    <p class="saveUrl"> {{saveFileUrl}}/tinypng</p>
                </div>
            </div>
        </div>
        </transition>
        <!-- 存在新的任务 -->
        <div class="modal " v-show="isShowTipsModal">
            <div class="tipsContent animated faster fadeInDown">
                <div class="header">
                    提示
                    <img class="closeIcon" src="./assets/close.png" @click="closeTips" />
                </div>
                <div class="tipsLineDiv">
                    <span>当前有压缩任务正在进行中,是否重新开始压缩任务?</span>
                </div>
                <div class="tipsLineIconDiv">
                    <img class="tipsClose" src="./assets/tipsClose.png" @click="closeTips" />
                    <img class="affirmIcon" src="./assets/confirm.png" @click='coverNewFile' />
                </div>
            </div>
        </div>
        <!-- 显示处理的结果页面 -->
        <div class="modal " v-show="isShowResultList">
            <div class="resultContet animated faster fadeInDown">
                <div class="header">
                    压缩完毕
                    <img class="closeIcon" src="./assets/close.png" @click="closeTips('result')" />
                </div>
                <div class="resultLineDiv">
                    <template v-for='item in newResult'>
                        <div class="resultList">
                            <div>
                                <img class='resultImg' v-bind:src="item.url" />
                            </div>
                            <div class="titleDiv">
                                <span class='img-title'>{{item.fileName}}</span>
                                <div>
                                    <span class='img-title fileSize'>{{item.oldSize}}</span>
                                    <span class='img-title fileSize'>{{item.newSize}}</span>
                                </div>
                            </div>
                            <span class='img-title ratio'>-{{item.ratio}}</span>
                        </div>

                    </template>
                </div>

            </div>
        </div>

        <div class="home">
            <!-- 小火箭 -->
            <div class="rocket-holder" v-if="!isLoading">
                <img class='rocket' src="./assets/rocket.png" />
                <img class="rainbow" src="./assets/rainbow.png" />
            </div>
            <div class="container" v-else>
                <span class="girl"></span>
                <div class="boys">
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
            </div>

            <!-- 提示文字 -->
            <div class="progressDiv">
                <div v-if="isLoading">
                    <p class="progress" v-if='!isEnd'>{{number}}/{{total}}</p>
                    <p class="progress" v-if='isEnd'>压缩完毕!</p>
                    <p class="progress" v-else>{{tipsTitle}}</p>
                </div>
                <div v-else>
                    <p class="progress">请拖入需要压缩的图片或者文件夹</p>
                </div>
            </div>
        </div>
    </div>
    <script>
        const TinyPng = require('web-tinypngjs');
        //本地桌面地址
        const path = require('path');
        const saveFileUrl = path.join(require('os').homedir(), 'Desktop');
        const {
            shell,
            Notification
        } = require('electron')
        const app = new Vue({
            el: '#vue',
            data: {
                total: 0,
                number: 0,
                saveFileUrl: saveFileUrl,
                isTemporaryFile: false,
                isLoading: false, //是否在压缩
                isEnd: false, //是否压缩结束
                isShowModal: false, //显示modal
                isShowTipsModal: false, //提示已经有任务
                isCover: true, //是否覆盖原来的图片
                tempInfo: null, //临时存放拖拽文件的地方
                tipsTitle: "正在压缩中...", //提示语
                imageResult: [], //存放处理后的文件信息
                newResult: [], //通知过后 重新组装的数据
                isShowResultList: false, //显示结果的列表页

            },
            created: function () {
                this.dropInit();
            },
            methods: {
                disposeTipsTitle: function () {
                    this.tipsTitle = '压缩后图片将保存在桌面tinypng文件中...'
                    setTimeout(() => {
                        this.tipsTitle = '正在压缩中...'
                    }, 5000)
                },
                //处理图片的方法-提取公共
                disposeImage: async function (e) {
                    const fileInfo = e.dataTransfer.files[0];
                    this.isLoading = true;
                    let isCover = this.isCover;
                    const {
                        name,
                        path,
                        type
                    } = fileInfo;
                    //如果是文件夹
                    if (type === '') {
                        const imageList = await TinyPng.getAllImg(path);
                        console.log('imageList', imageList);
                        //判断是否有store文件
                        if (imageList.length > 0) {
                            this.total = imageList.length
                        }
                        if (imageList.length === 0) {
                            alert('文件夹里面未搜索到图片哦~')
                        } else {
                            let isTemporaryFile = false;
                            imageList.find((item) => {
                                if (item.name === ".DS_Store") {
                                    isTemporaryFile = true;
                                }
                                this.total = isTemporaryFile ? imageList.length - 1 : imageList.length;
                                this.isEnd = false;
                                this.isTemporaryFile = isTemporaryFile;
                            })
                            this.disposeTipsTitle();
                            //如果需要覆盖的话 输出地址不传
                            TinyPng.compress(path, isCover ? '' : `${this.saveFileUrl}/tinypng`, this.process);
                        }
                    } else if (type.includes("image")) {
                        this.isEnd = false;
                        this.number = 1;
                        this.total = 1;
                        this.disposeTipsTitle();
                        console.log('111')
                        //如果需要覆盖的话 输出地址不传
                        TinyPng.compressImg(path, isCover ? "" : `${this.saveFileUrl}/tinypng/${name}`).then((res) => {
                            console.log('222')
                            this.isEnd = true;
                            this.isLoading = false;
                            if (res) {
                                this.imageResult.push(res)
                            }
                            this.messageNotice();
                        });
                    } else {
                        alert("不是图片哦")
                    }
                },
                // 拖拽初始化
                dropInit: function () {
                    document.addEventListener("drop", preventDe);
                    document.addEventListener("dragleave", preventDe);
                    document.addEventListener("dragover", preventDe);
                    document.addEventListener("dragenter", preventDe);

                    function preventDe(e) {
                        e.preventDefault();
                    }

                    document.addEventListener("drop", async (e) => {
                        e.preventDefault();
                        if (this.isLoading) {
                            this.isShowTipsModal = true;
                            this.tempInfo = e.dataTransfer.files[0];
                        } else {
                            this.disposeImage(e);
                        }
                    })
                },
                // 页面回调
                process: function (res, number, total) {

                    //處理下文件的名稱
                    //如果有临时文件 数量-1
                    if (this.isTemporaryFile) {
                        --total;
                        --number;
                    }
                    if (res) {
                        this.imageResult.push(res)
                    }
                    this.number = number;
                    this.total = total;
                    if (number === total) {
                        this.isLoading = false;
                        this.isEnd = true;
                        this.total = 0;
                        this.number = 0;
                        this.messageNotice();
                    }
                },
                showSetting: function () {
                    this.isShowModal = true;
                },
                closeSetting: function () {
                    this.isShowModal = false;
                },
                closeTips: function (type) {

                    if (type === 'result') {
                        this.isShowResultList = false;
                        this.newResult = [];
                    } else {
                        this.isShowTipsModal = false;
                    }

                },
                coverNewFile: function () {
                    this.total = 0;
                    this.number = 0;
                    this.isShowTipsModal = false;
                    let tempInfo = this.tempInfo;
                    const data = {
                        dataTransfer: {
                            files: [tempInfo]
                        }
                    }
                    this.disposeImage(data)
                },
                //消息通知
                messageNotice: function () {
                    let disposerNumber = 0;
                    let compressionSize = 0;
                    let compressionSizeDesc = '';

                    this.imageResult.map((item) => {
                        ++disposerNumber;
                        compressionSize += (item.input.size - item.output.size);
                        compressionSizeDesc = this.getFileSize(compressionSize);
                    })
                    let option = {
                        title: "文件压缩成功!",
                        body: `本次共压缩了${disposerNumber}个文件夹,共计压缩${compressionSizeDesc}`,
                        icon: path.join(__dirname, './assets/programming.png')
                    };
                    // 创建通知并保存
                    let hhwNotication = new window.Notification(option.title, option);
                    //通知过后-重新组装数据下
                    let newResult = []
                    this.imageResult.map((item) => {
                        let oldSize = this.getFileSize(item.input.size);
                        let newSize = this.getFileSize(item.output.size);
                        let ratio = this.toPercent((item.input.size - item.output.size) / item.input.size);
                        let fileName = item.fileName.split(".")[0]
                        newResult.push({
                            url: item.output.url,
                            fileName: fileName,
                            oldSize,
                            newSize,
                            ratio
                        })
                    })
                    this.newResult = newResult;
                    this.isShowResultList = true;
                    this.imageResult = [];
                    // 当通知被点击时, 用默认浏览器打开链接
                    hhwNotication.onclick = function () {
                        console.log("点击了吧")

                    }

                },
                //获取文件多少kb
                getFileSize: function (fileByte) {
                    var fileSizeByte = fileByte;
                    var fileSizeMsg = "";
                    if (fileSizeByte < 1048576) fileSizeMsg = (fileSizeByte / 1024).toFixed(2) + "KB";
                    else if (fileSizeByte == 1048576) fileSizeMsg = "1MB";
                    else if (fileSizeByte > 1048576 && fileSizeByte < 1073741824) fileSizeMsg = (fileSizeByte / (1024 * 1024)).toFixed(2) + "MB";
                    else if (fileSizeByte > 1048576 && fileSizeByte == 1073741824) fileSizeMsg = "1GB";
                    else if (fileSizeByte > 1073741824 && fileSizeByte < 1099511627776) fileSizeMsg = (fileSizeByte / (1024 * 1024 * 1024)).toFixed(2) + "GB";
                    else fileSizeMsg = "文件超过1TB";
                    return fileSizeMsg;
                },
                //转成百分数
                toPercent: function (point) {
                    var str = Number(point * 100).toFixed(1);
                    str += "%";
                    return str;
                }
            }

        })
    </script>



</body>

</html>